package com.sky.utils.admin;

import cn.hutool.core.util.ObjectUtil;
import com.sky.constant.JwtClaimsConstant;
import com.sky.entity.Employee;
import com.sky.properties.JwtProperties;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Component
@Slf4j
public class EmployeeUtil {

    @Resource
    private JwtProperties jwtProperties;
    @Resource
    private EmployeeService employeeService;

    public Long getEmployeeId(HttpServletRequest request) {
        String token = request.getHeader(jwtProperties.getAdminTokenName());
        Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
        Object value = claims.get(JwtClaimsConstant.EMP_ID);
        if (ObjectUtil.isNotEmpty(value)) {
            Long empId = Long.valueOf(String.valueOf(value));
            return empId;
        }
        log.error("未从token中获取到员工id.....");
        return null;
    }

    //获取当前操作人名称
    public String getEmployeeName(HttpServletRequest request) {
        Long empId = getEmployeeId(request);
        if(empId == null) {
            return null;
        }
        Employee employee = employeeService.getEmployeeById(empId);
            if (ObjectUtil.isEmpty(employee)) {
                log.error("token中获取的员工id查询员工为空! 员工id为:{}",empId);
                throw new RuntimeException("非法操作");
            }
            return employee.getName();
        }
    }
